package com.xqc.utils;

import com.xqc.bean.TableDefinitionBean;
import com.xqc.jdbc.JdbcCloseUtils;
import com.xqc.jdbc.JdbcConnUtils;
import org.springframework.util.StringUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class TableUtils {

    /**
     * 获取数据库所有表名称
     */
    public static List<String> getTables(){
        List<String> tableNames = new ArrayList<>();
        Connection conn = JdbcConnUtils.getConnection();
        DatabaseMetaData metaData = null;
        try {
            metaData = conn.getMetaData();
            ResultSet rs = metaData.getTables(null, null, null, new String[]{"TABLE"});
            while(rs.next()){
                //获取表名称
                tableNames.add(rs.getString(3));
            }
            JdbcCloseUtils.closeAll(conn, null, rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tableNames;
    }

    /**
     * 获取数据库表对应的字段
     */
    public static List<TableDefinitionBean> tableDefinitionBeans(String tableName){
        List<TableDefinitionBean> tableDefinitionBeans = new ArrayList<>();
        try {
            Connection conn = JdbcConnUtils.getConnection();
            String sql = "show full columns from "+tableName;
            PreparedStatement ps = null;
            ps = conn.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            TableDefinitionBean tableDefinitionBean;
            while(rs.next()){
                tableDefinitionBean = new TableDefinitionBean();
                tableDefinitionBean.setFieldName(rs.getString("Field"));
                tableDefinitionBean.setFieldType(rs.getString("Type"));
                tableDefinitionBean.setComment(rs.getString("Comment"));
                tableDefinitionBean.setKey(rs.getString("Key"));
                tableDefinitionBean.setExtra(rs.getString("Extra"));
                tableDefinitionBeans.add(tableDefinitionBean);
            }
            JdbcCloseUtils.closeAll(conn, ps, rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tableDefinitionBeans;
    }

    public static String subFieldType(String fieldType){
        if(StringUtils.isEmpty(fieldType)){
            return null;
        }
        return fieldType.split("\\(")[0];
    }
}
